// src/components/popups/userActions/ChangePwd.tsx

import { useState } from 'react';
import type { FC } from 'react';
import { FaEye, FaEyeSlash } from 'react-icons/fa';
import { changePassword } from '@/services/authService';
import type { ChangePasswordRequest } from '@/types/types';

interface ChangePwdProps {
  onClose: () => void;
}

const ChangePwd: FC<ChangePwdProps> = ({ onClose }) => {
  const [formData, setFormData] = useState({
    originPwd: '',
    newPwd: '',
    confirmPwd: '',
  });

  const [showPwd, setShowPwd] = useState(false);

  const [error, setError] = useState('');
  const [message, setMessage] = useState('');

  const handleChange = (field: keyof typeof formData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const validateForm = () => {
    const { originPwd, newPwd, confirmPwd } = formData;
    const pwdRegex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&]).{8,}$/;

    if (!originPwd || !newPwd || !confirmPwd) return 'All fields are required';
    if (newPwd !== confirmPwd) return 'New passwords do not match';
    if (!pwdRegex.test(newPwd)) {
      return 'Password must be at least 8 characters, with letters, numbers, and symbols';
    }
    return '';
  };

  const handleSubmit = async () => {
    const validationError = validateForm();
    if (validationError) {
      setError(validationError);
      return;
    }

    const token = localStorage.getItem('token');
    if (!token) {
      setError('No token found');
      return;
    }

    try {
      const payload: ChangePasswordRequest = {
        old_password: formData.originPwd,
        new_password: formData.newPwd,
      };

      await changePassword(payload, token);

      setMessage('Password changed successfully!');
      setError('');
      setFormData({ originPwd: '', newPwd: '', confirmPwd: '' });

      setTimeout(() => {
        onClose();
      }, 1000);
    } catch (err) {
      console.error('Failed to update password:', err);
      setError('Failed to change password');
    }
  };

  return (
    <div className="p-6 sm:p-8 space-y-6 text-gray-800 dark:text-gray-100 font-poppins">
      {/* Toast message */}
      {message && (
        <div className="fixed top-6 left-1/2 transform -translate-x-1/2 bg-green-600 dark:bg-emerald-700 text-white px-4 py-2 rounded-xl shadow-lg z-50 animate-fade-in">
          {message}
        </div>
      )}

      {/* Header */}
      <h2 className="text-xl sm:text-2xl font-semibold text-center text-gray-800 dark:text-cyan-200">Change Password</h2>

      {/* Form */}
      <div className="space-y-5">
        {[
          { label: 'Original Password', field: 'originPwd' },
          { label: 'New Password', field: 'newPwd' },
          { label: 'Confirm New Password', field: 'confirmPwd' },
        ].map(({ label, field }) => (
          <div key={field}>
            <label className="block text-sm font-medium text-gray-600 dark:text-gray-300 mb-1">{label}</label>
            <div className="relative">
              <input
                type={field === 'originPwd' && showPwd ? 'text' : 'password'}
                value={formData[field as keyof typeof formData]}
                onChange={(e) => handleChange(field as keyof typeof formData, e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 dark:border-slate-700 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:focus:ring-cyan-700 bg-white dark:bg-slate-800 text-gray-800 dark:text-gray-100"
              />
              {field === 'originPwd' && (
                <button
                  type="button"
                  onClick={() => setShowPwd(!showPwd)}
                  className="absolute right-3 top-2.5 text-gray-500 dark:text-gray-300"
                >
                  {showPwd ? <FaEyeSlash /> : <FaEye />}
                </button>
              )}
            </div>
          </div>
        ))}

        {error && <p className="text-sm text-red-500 dark:text-red-400">{error}</p>}
      </div>

      {/* Actions */}
      <div className="flex justify-end mt-6 gap-3">
        <button
          onClick={onClose}
          className="px-4 py-2 rounded-xl border border-gray-300 dark:border-slate-700 text-gray-600 dark:text-gray-200 hover:text-gray-800 dark:hover:text-cyan-300 bg-white dark:bg-slate-800 transition"
        >
          Back
        </button>
        <button
          onClick={handleSubmit}
          className="px-6 py-2 rounded-xl text-white font-medium bg-indigo-600 dark:bg-cyan-700 hover:bg-indigo-700 dark:hover:bg-cyan-800 transition shadow-md"
        >
          Confirm
        </button>
      </div>
    </div>
  );
};

export default ChangePwd;